import React, { useEffect, useState } from 'react'
import Message from '../../components/Message';
import AppDialog from '../../components/AppDialog'
import { Button, Form, Input, Space } from 'antd';
import { addParams, editParams } from "../../api/params.js";

const AddOrEditParam = (props) => {
  const [loading, setLoading] = useState(false)
  const [form] = Form.useForm();
  const tailLayout = {
    wrapperCol: {
      offset: 10,
      span: 14,
    },
  };

  useEffect(() => {
    if (props.visible && props.attrInfo !== null) {
      const initialValues = {
        attr_name: props.attrInfo.attr_name
      }
      form.setFieldsValue(initialValues)
    }
  }, [props.attrInfo])

  // 点击确定
  const onFinish = async (values) => {
    setLoading(true)
    if (props.attrInfo !== null) {
      const data = {...props.attrInfo};
      data.attr_name = values.attr_name
      if (data.attr_vals.length === 0) {
        delete(data.attr_vals)
      }
      // 更新
      await editParams(props.cateId, data).finally(() => {
        setLoading(false)
      });
      Message("success", "编辑成功");
    } else {
      const data = {
        attr_name: values.attr_name,
        attr_sel: props.activeKey,
      };
      // 添加
      await addParams(props.cateId, data).finally(() => {
        setLoading(false)
      });
      Message("success", "添加成功");
    }
   
    handleDialogClosed('success')
  };

  // 提交表单且数据验证失败后回调事件
  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  // 点击取消
  const handleDialogClosed = (type) => {
    form.resetFields();
    props.onHide(type)
  };

  return ( props.visible ? 
    <AppDialog
      title={props.attrInfo !== null ? '编辑' : '添加' + props.titleText}
      visible={props.visible}
      onClosed={handleDialogClosed}
    >
      <Form
        form={form}
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 20 }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
      >
        <Form.Item
          label={props.titleText}
          name="attr_name"
          rules={[{ required: true, message: '请输入'+ props.titleText }]}
        >
          <Input />
        </Form.Item>
        <Form.Item {...tailLayout}>
          <Space>
            <Button type="primary" htmlType="submit" loading={loading}>确定</Button>
            <Button onClick={() => handleDialogClosed()}>取消</Button>
          </Space>
        </Form.Item>
      </Form>
    </AppDialog>
    : null
  )
}

export default AddOrEditParam